package com.lidong.framework.util;

import javax.servlet.http.HttpServletRequest;

public class AddressUtil {
	
	private final static long IP_LONG_MIN = 0;
	private final static long IP_LONG_MAX = 4294967295L;
	/**
	 * 获取客户端ip
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");   
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	        ip = request.getHeader("Proxy-Client-IP");   
	    }   
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	        ip = request.getHeader("WL-Proxy-Client-IP");   
	    }   
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	        ip = request.getRemoteAddr();   
	    }
	    return ip;
	}
	
	/**
	 * 获取客户端ip
	 * @param request
	 * @return
	 */
	public static String getFirstIpAddress(HttpServletRequest request) {
		String ip = getIpAddress(request);
	    if(StringUtil.isNotBlank(ip) && ip.indexOf(",") != -1){
	    	ip = ip.split(",")[0].trim();
	    }
	    return ip;
	}
	
	/**
	 * 将长整型的ip转换为字符串类型
	 * @param ipLong
	 * @return
	 */
	public static String parseLong2Ip(long ipLong) {
		if(ipLong <= IP_LONG_MIN || ipLong > IP_LONG_MAX){
			return null;
		}
		StringBuilder ipbBuilder = new StringBuilder(15);
		ipbBuilder.append((ipLong >>> 24) & 0xff);
		ipbBuilder.append(".");
		ipbBuilder.append((ipLong >>> 16) & 0xff);
		ipbBuilder.append(".");
		ipbBuilder.append((ipLong >>> 8) & 0xff);
		ipbBuilder.append(".");
		ipbBuilder.append(ipLong & 0xff);
		return ipbBuilder.toString();
	}
	/**
	 * 将127.0.0.1类型地址转换为长整形
	 * @param ipAddr
	 * @return
	 */
	public static long parseIp2Long(String ipAddr) {
		if(!ipAvailable(ipAddr)){
			return 0L;
		}
        String[] ipArr = ipAddr.split("\\.");
        long ipLong = 0;
        ipLong += Long.parseLong(ipArr[0]) << 24;
        ipLong += Long.parseLong(ipArr[1]) << 16;
        ipLong += Long.parseLong(ipArr[2]) << 8;
        ipLong += Long.parseLong(ipArr[3]);
        if(ipLong > IP_LONG_MAX){
        	return 0L;
        }
        return ipLong;
	}
	/**
	 * 判断ip是否有效
	 * @param ipAddr
	 * @return
	 */
	public static boolean ipAvailable(String ipAddr){
		if(StringUtil.isBlank(ipAddr)){
			return false;
		}
		if(!ipAddr.matches("^(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)){3}$")){
			return false;
		}
		return true;
	}
	/**
	 * 判断mac地址是否有效
	 * @param mac
	 * @return
	 */
	public static boolean macAvailable(String mac){
		if(StringUtil.isBlank(mac)){
			return false;
		}
		if(!mac.matches("^(([a-fA-F0-9]){2})(-([a-fA-F0-9]){2}){5}$")){
			return false;
		}
		return true;
	}
	
	public static void main(String[] args) {
		System.out.println(parseIp2Long("10.10.1.1"));
		System.out.println(ipAvailable(""));
	}
}
